//app.js
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function (res) {
          that.globalData.code = res.code
          wx.getUserInfo({
            success: function (res) {
              that.globalData.iv = res.iv
              that.globalData.encryptedData = res.encryptedData
              that.get3rdSession(cb)
            }
          })
        }
      })
    }
  },
  getLocation:function(cb){
    var that = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        that.globalData.latitude = res.latitude
        that.globalData.longitude = res.longitude
        cb(res)
      }
    })
  },
  get3rdSession: function (cb) {
    let that = this
    wx.request({
      url: that.globalData.path + '/weixin/coffee/xcx/user/get3rdSession',
      data: {
        code: this.globalData.code
      },
      method: 'GET',
      success: function (res) {
        var sessionId = res.data.session;
        that.globalData.sessionId = sessionId
        wx.setStorageSync('sessionId', sessionId)
        that.decodeUserInfo(cb)
      }
    })
  },
  decodeUserInfo: function (cb) {
    let that = this
    wx.request({
      url: that.globalData.path + '/weixin/coffee/xcx/user/decodeUserInfo',
      data: {
        encryptedData: that.globalData.encryptedData,
        iv: that.globalData.iv,
        session: wx.getStorageSync('sessionId')
      },
      method: 'GET',
      success: function (res) {
        that.globalData.userInfo = res.data
        typeof cb == "function" && cb(that.globalData.userInfo)
      }
    })
  },
  globalData: {
    userInfo: null,
    iv: null,
    encryptedData: null,
    sessionId: null,
    latitude: null,
    longitude: null,
    path: 'https://app.wishtv.com.cn'
    //path:'https://test.wishtv.com.cn'
    //path: 'http://localhost'
  }
})